<template>
  <NConfigProvider
    :locale="projectStore.language === 'zh' ? zhCN : null"
    :theme="getDarkTheme"
    :theme-overrides="getThemeOverrides"
    :date-locale="projectStore.language === 'zh' ? dateZhCN : null"
  >
    <AppProvider>
      <RouterView />
    </AppProvider>
  </NConfigProvider>
</template>

<script lang="ts" setup>
  import { computed } from 'vue';
  import { zhCN, dateZhCN, darkTheme } from 'naive-ui';
  import { AppProvider } from '@/components/Application';
  import { useDesignSettingStore } from '@/store/modules/designSetting';
  import { useProjectSettingStore } from '@/store/modules/projectSetting';
  import { lighten } from '@/utils/index';
  import { usePlcWithOut } from '@/store/modules/plc';
  import { t } from '@/i18n';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { updateAlarmRecord } from '@/api/wip/alarmRecord';
  import { addMachineStatus } from './api/reportForm/periodStatusMonitoring';

  const designStore = useDesignSettingStore();
  const projectStore = useProjectSettingStore();
  const plcStore = usePlcWithOut();
  const userStore = useUserStoreWidthOut();

  const $message = window['$message'];

  const $dialog = window['$dialog'];

  const machineStatus = ref(null);

  // console.log($message)

  if (window.electron) {
    const {
      onUpdateData,
      plcClick,
      onMessageData,
      plcReConnect,
      getPlcData,
      onHostOnline,
      onHostOffline,
      reload,
      plcConnect,
      deleteChildProcess,
    } = window.electron || {};

    provide('plcClick', plcClick);

    plcReConnect();

    provide('plcReConnect', plcReConnect);

    projectStore.plcConnect = plcConnect;

    projectStore.deleteChildProcess = deleteChildProcess;

    const { machineAlarmList, machineData } = projectStore;

    const alarmObj = {};

    const alarmList = [];

    let changeAlarmList = [];

    if (machineData) {
      const { machineCode, machineStatusNegation } = machineData;

      if (machineAlarmList.length) {
        for (const item of machineAlarmList) {
          const { alarmCode } = item;

          alarmObj[alarmCode] = null;
        }
      }

      onUpdateData((data) => {
        const { equipmentStatusGet = null } = data;

        if (equipmentStatusGet !== null) {
          let machineStatusBoolVal = Number(data['equipmentStatusGet']) === 1;

          if (machineStatusNegation === 1) {
            machineStatusBoolVal = !machineStatusBoolVal;
          }

          if (machineStatusBoolVal !== machineStatus.value) {
            machineStatus.value = machineStatusBoolVal;
            // todo
            addMachineStatus({
              machineCode,
              machineStatus:machineStatusBoolVal
            })
          }
        }

        for (const i in alarmObj) {
          if (data[i] !== undefined && alarmObj[i] !== data[i]) {
            const obj = machineAlarmList.find((item) => item.alarmCode === i);

            console.log(alarmList);

            if (obj) {
              changeAlarmList.push({
                ...obj,
                alarmStatus: data[i],
              });
            }

            alarmObj[i] = data[i];

            if (alarmObj[i] === '1') {
              const obj = alarmList.find((item) => item.alarmCode === i);

              if (!obj) {
                alarmList.push(toRaw(machineAlarmList.find((item) => item.alarmCode === i)));
              }
            } else if (alarmObj[i] === '0') {
              const index = alarmList.findIndex((item) => item.alarmCode === i);

              if (index !== -1) {
                alarmList.splice(index, 1);
              }
            }
          }
        }

        console.log(data);

        if (changeAlarmList.length) {
          // 请求
          updateAlarmRecord({
            machineCode,
            changeAlarmList,
          });

          changeAlarmList = [];
        }

        plcStore.updateNewData(data);

        projectStore.updateAlarmList(alarmList);
      });
    }

    onMessageData((data) => {
      const { success, type, name } = data;

      if (type === 'write') {
        const messageType = success ? 'success' : 'error';

        $message.destroyAll();

        $message[messageType](t(`common.tipMsg.${success ? 'isSucc' : 'isErr'}`));
      } else if (type === 'isOnline') {
        if (success) {
          plcStore.setIsOnLine(true);

          plcStore.removeNotOnlineNameFn(name);
        } else {
          plcStore.setIsOnLine(false);

          plcStore.setNotOnlineNameFn(name);
        }
      }
    });

    let showHostOnlineModal = false;

    onHostOnline((data) => {
      if (!showHostOnlineModal) {
        showHostOnlineModal = true;

        $dialog.destroyAll();

        $dialog.warning({
          title: t('common.tipMsg.warning'),
          content: t('common.tipMsg.hostOnlineMsg').replace('{{host}}', data),
          positiveText: t('common.tipMsg.sure'),
          negativeText: t('common.tipMsg.cancel'),
          onPositiveClick: () => {
            userStore.clearAll();

            reload();
          },
          onNegativeClick: () => {},
        });
      }
    });

    let showHostOfflineModal = false;

    onHostOffline((data) => {
      if (!showHostOfflineModal) {
        showHostOfflineModal = true;

        $dialog.destroyAll();

        $dialog.warning({
          title: t('common.tipMsg.warning'),
          content: t('common.tipMsg.hostOfflineMsg').replace('{{host}}', data),
          positiveText: t('common.tipMsg.sure'),
          negativeText: t('common.tipMsg.cancel'),
          onPositiveClick: () => {
            userStore.clearAll();

            reload();
          },
          onNegativeClick: () => {},
        });
      }
    });

    nextTick(() => {
      getPlcData && getPlcData();
    });
  }

  /**
   * @type import('naive-ui').GlobalThemeOverrides
   */
  const getThemeOverrides = computed(() => {
    const appTheme = designStore.appTheme;
    const lightenStr = lighten(designStore.appTheme, 6);
    return {
      common: {
        primaryColor: appTheme,
        primaryColorHover: lightenStr,
        primaryColorPressed: lightenStr,
      },
      LoadingBar: {
        colorLoading: appTheme,
      },
    };
  });

  const getDarkTheme = computed(() => (designStore.darkTheme ? darkTheme : undefined));
</script>

<style lang="less">
  @import 'styles/index.less';
</style>
